package com.huizu.project.service.impl;

import com.github.pagehelper.PageInfo;
import com.huizu.common.core.domain.entity.SysUser;
import com.huizu.common.exception.ServiceException;
import com.huizu.common.utils.DateUtils;
import com.huizu.common.utils.SecurityUtils;
import com.huizu.common.utils.SnowFlake;
import com.huizu.project.domain.*;
import com.huizu.project.mapper.*;
import com.huizu.project.service.IProUserService;
import com.huizu.project.service.IProXyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 学院管理Service业务层处理
 *
 * @author zhangmx
 * @date 2024-05-11
 */
@Service
public class ProXyServiceImpl implements IProXyService
{
    @Autowired
    private ProXyMapper proXyMapper;

    @Autowired
    private ProNjMapper proNjMapper;

    @Autowired
    private IProUserService proUserService;

    @Autowired
    private SysUserAuthMapper sysUserAuthMapper;

    @Autowired
    private SysUserApiMapper sysUserApiMapper;

    @Autowired
    private ProUserMapper proUserMapper;

    @Autowired
    private ProBjMapper proBjMapper;

    /**
     * 查询学院管理
     *
     * @param id 学院管理主键
     * @return 学院管理
     */
    @Override
    public ProXy selectProXyById(String id)
    {
        return proXyMapper.selectProXyById(id);
    }

    /**
     * 查询学院管理列表
     *
     * @param proXy 学院管理
     * @return 学院管理
     */
    @Override
    public List<ProXy> selectProXyList(ProXy proXy)
    {
        return proXyMapper.selectProXyList(proXy);

    }
    @Override
    public List<ProXy> selectProXyListByNumberNoId(ProXy proXy){
        return proXyMapper.selectProXyListByNumberNoId(proXy.getNumber(),proXy.getId());
    }


    /**
     * 新增学院管理
     *
     * @param proXy 学院管理
     * @return 结果
     */
    @Override
    public int insertProXy(ProXy proXy)
    {
        proXy.setId(String.valueOf(SnowFlake.nextId()));
        proXy.setCreateTime(DateUtils.getNowDate());

        //新增分配权限
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysUserAuth sysUserAuth = new SysUserAuth();
        sysUserAuth.setUserId(user.getUserId());
        sysUserAuth.setBusId(proXy.getId());
        sysUserAuth.setType("xy");
        sysUserAuthMapper.insertSysUserAuth(sysUserAuth);
        return proXyMapper.insertProXy(proXy);
    }

    /**
     * 修改学院管理
     *
     * @param proXy 学院管理
     * @return 结果
     */
    @Override
    public int updateProXy(ProXy proXy)
    {
        return proXyMapper.updateProXy(proXy);
    }

    /**
     * 批量删除学院管理
     *
     * @param ids 需要删除的学院管理主键
     * @return 结果
     */
    @Override
    public int deleteProXyByIds(String[] ids)
    {
        for (String id : ids) {
            ProNj proNjPram = new ProNj();
            proNjPram.setpId(id);
            List<ProNj> proNjList = proNjMapper.selectProNjList(proNjPram);
            if (!proNjList.isEmpty()) {
                throw new ServiceException("学院名下有未删除的年级，不允许删除");
            }
            SysUser sysUser = new SysUser();
            sysUser.setXyId(id);
            List<SysUser> list = sysUserApiMapper.selectSysUserList(sysUser);
            if (list.size() > 0) {
                throw new ServiceException("学院名下有教师，不允许删除");
            }
            ProUser proUser = new ProUser();
            proUser.setXyId(id);
            List<ProUser> proUsers = proUserMapper.selectProUserList(proUser);
            if (proUsers.size() > 0) {
                throw new ServiceException("学院名下有学生，不允许删除");
            }
        }
        return proXyMapper.deleteProXyByIds(ids);
    }

    /**
     * 删除学院管理信息
     *
     * @param id 学院管理主键
     * @return 结果
     */
    @Override
    public int deleteProXyById(String id)
    {
        ProNj proNjPram = new ProNj();
        proNjPram.setpId(id);
        List<ProNj> proNjList = proNjMapper.selectProNjList(proNjPram);
        if (!proNjList.isEmpty())
            throw new ServiceException("学院名下有未删除的年级，不允许删除");
        return proXyMapper.deleteProXyById(id);
    }

    @Override
    public BaseVo getSchoolDcList(String id) {
        ProXy proXy = new ProXy();
        proXy.setId(id);
        List<ProXy> list = proXyMapper.selectProXyList(proXy);
        long total = new PageInfo(list).getTotal();
        ArrayList<ProUserSchoolDcVo> proUserSchoolDcVos = new ArrayList<>();

        list.forEach(proXy1 -> {
            // 总进度
            String allSchedule = calculateAllSchedule(proXy1.getId());
            ProUserSchoolDcVo proUserSchoolDcVo = ProUserSchoolDcVo.builder()
                    .id(proXy1.getId())
                    .adminUserId(proXy1.getAdminUserId())
                    .schoolName(proXy1.getName())
                    .adminName(proXy1.getAdminUserName())
                    .AllSchedule(allSchedule)
                    .number(proXy1.getNumber())
                    .jsNumber(proXy1.getJsNumber())
                    .build();
            proUserSchoolDcVos.add(proUserSchoolDcVo);
        });

        return BaseVo.builder()
                .total(total)
                .list(proUserSchoolDcVos)
                .build();
    }

    @Override
    public ProUserSchoolDcVo getDetail(String id) {
        ProXy proXy = proXyMapper.selectProXyById(id);

        if (proXy == null) {
            throw new ServiceException("无法获取督促详情");
        }
        return ProUserSchoolDcVo.builder()
                .id(proXy.getId())
                .schoolName(proXy.getName())
                .adminName(proXy.getAdminUserName())
                .AllSchedule(calculateAllSchedule(proXy.getId()))
                .build();
    }

    // 获取总得分信息
    private String calculateAllSchedule(String id) {
        ProBj proBj = new ProBj();
        proBj.setXyid(id);
        List<ProBj> bjList = getBjList(proBj);
        //总劳动得分
//        double sumNumber = 0;
        BigDecimal sumNumber = BigDecimal.ZERO;
        //总人数
//        double sumUsers = 0;
        BigDecimal sumUsers = BigDecimal.ZERO;
        for (ProBj bj : bjList) {
            sumNumber = sumNumber.add(bjAllSchedule(bj.getJdCount(),bj.getUserCount()));
            sumUsers = sumUsers.add(new BigDecimal(bj.getUserCount()));
        }
        BigDecimal result = sumNumber.signum() != 0 && sumUsers.signum() != 0
                ? sumNumber.divide(sumUsers, 2, RoundingMode.HALF_UP)
                : new BigDecimal(0);
        BigDecimal percentage = result.multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP);
        return percentage.toString() + "%";
    }

    /**
     * 获取班级列表(性能优化)
     * @param proBjParam 查询参数
     * @return 班级列表
     */
    public List<ProBj> getBjList(ProBj proBjParam) {
        // 1. 查询所有相关的 ProBj 数据
        List<ProBj> proBjs = proBjMapper.selectProBjList(proBjParam);

        // 2. 提取所有 ProBj 的 ID，用于批量查询 ProUser 数据
        List<String> bjIds = proBjs.stream().map(ProBj::getId).collect(Collectors.toList());

        // 3. 批量查询所有相关的 ProUser 数据
        ProUser proUserParam = new ProUser();
        proUserParam.setBjIds(bjIds); // 假设 ProUser 类支持批量查询
        List<ProUser> users = proUserMapper.selectProUserList(proUserParam);

        // 4. 将 ProUser 数据按班级 ID 分组
        Map<String, List<ProUser>> userMap = users.stream()
                .collect(Collectors.groupingBy(ProUser::getClId));

        // 5. 遍历 ProBj 列表，计算每个班级的进度
        for (ProBj proBj : proBjs) {
            List<ProUser> usersInBj = userMap.getOrDefault(proBj.getId(), Collections.emptyList());

            BigDecimal totalPer = BigDecimal.ZERO;
            int totalNum = usersInBj.size();

            for (ProUser user : usersInBj) {
                // 计算每个用户的进度权重
                BigDecimal countPer = user.getJcldJdPer().multiply(BigDecimal.valueOf(0.48))
                        .add(user.getLdzjJdPer().multiply(BigDecimal.valueOf(0.16)))
                        .add(user.getLdcgJdPer().multiply(BigDecimal.valueOf(0.08)))
                        .add(user.getLdgyJdPer().multiply(BigDecimal.valueOf(0.08)))
                        .add(user.getLlcjJdPer().multiply(BigDecimal.valueOf(0.20)));
                totalPer = totalPer.add(countPer);
            }

            // 设置班级的进度
            if (totalNum == 0) {
                proBj.setJdCount(BigDecimal.ZERO);
            } else {
                proBj.setJdCount(totalPer.divide(BigDecimal.valueOf(totalNum), 2, RoundingMode.HALF_UP));
            }
        }

        return proBjs;
    }


    // 计算班级总得分
    public BigDecimal bjAllSchedule(BigDecimal percentage, Integer number) {
        // 将百分比转换为小数
        BigDecimal decimalPercentage = percentage.divide(new BigDecimal("100"));
        // 将整数转换为 BigDecimal
        BigDecimal decimalNumber = new BigDecimal(number);
        BigDecimal result = decimalPercentage.multiply(decimalNumber);
        return result;
    }

}
